﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Text.Json;
using System.Threading.Tasks;

namespace PHMEE.Videos
{
    /// <summary>
    /// 将枚举类型JsonConverter转换时，全部小写
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class JsonStringEnumConverterLowercase<T> : JsonConverter<T> where T : struct, Enum
    {
        public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var value = reader.GetString();
            if (Enum.TryParse(typeof(T), value, true, out var result))
            {
                return (T)result;
            }
            throw new JsonException($"无法把\"{value}\"转换为枚举  \"{typeof(T)}\".");
        }

        public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString().ToLower());
        }
    }

}
